package com.artron.mediaartron.ui.fragment.home;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.image.ImageUtils;
import com.artron.baselib.utils.ToastUtil;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.LoginData;
import com.artron.mediaartron.data.entity.User;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.activity.MainActivity;
import com.artron.mediaartron.ui.callback.MainActivityCallback;
import com.artron.mediaartron.ui.fragment.center.UserInfoFragment;
import com.artron.mediaartron.ui.fragment.login.NoLoginFragment;
import com.artron.mediaartron.util.CacheUtils;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;


/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-09-20.
 */

public class MyCenterFragment extends BaseStaticFragment implements View.OnClickListener, MainActivityCallback {

    @BindView(R.id.MyCenterFragment_iv_user_icon)
    protected ImageView mIvUserIcon;
    @BindView(R.id.MyCenterFragment_tv_user_name)
    protected TextView mTvUserName;
    @BindView(R.id.MyCenterFragment_tv_profile)
    protected TextView mTvProfile;
    @BindView(R.id.MyCenterFragment_rl_user_info)
    protected RelativeLayout mRlUserInfo;
    @BindView(R.id.MyCenterFragment_tv_my_works)
    protected TextView mTvMyWorks;
    @BindView(R.id.MyCenterFragment_tv_material_depot)
    protected TextView mTvMaterialDepot;
    @BindView(R.id.MyCenterFragment_tv_order_all)
    protected TextView mTvOrderAll;
    @BindView(R.id.MyCenterFragment_tv_account_paid)
    protected TextView mTvAccountPaid;
    @BindView(R.id.MyCenterFragment_tv_obligation)
    protected TextView mTvObligation;
    @BindView(R.id.MyCenterFragment_tv_canceled)
    protected TextView mTvCanceled;
    @BindView(R.id.MyCenterFragment_tv_address)
    protected TextView mTvAddress;
    @BindView(R.id.MyCenterFragment_tv_coupons)
    protected TextView mTvCoupons;
    @BindView(R.id.MyCenterFragment_tv_cache)
    protected TextView mTvCache;
    @BindView(R.id.MyCenterFragment_rl_clear_cache)
    protected RelativeLayout mRlClearCache;
    @BindView(R.id.MyCenterFragment_tv_feedback)
    protected TextView mTvFeedback;
    @BindView(R.id.MyCenterFragment_rl_phone)
    protected RelativeLayout mRlPhone;
    @BindView(R.id.MyCenterFragment_iv_go)
    protected ImageView mIvGo;
    @BindView(R.id.MyCenterFragment_tv_no_login)
    protected TextView mTvNoLogin;
    @BindView(R.id.MyCenterFragment_tv_order_text)
    protected TextView mTvOrderText;

    private LoginData mLoginData;

    public static MyCenterFragment newInstance() {
        return new MyCenterFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_center;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    protected void initView() {
        mRlUserInfo.setOnClickListener(this);
        mTvMyWorks.setOnClickListener(this);
        mTvMaterialDepot.setOnClickListener(this);
        mTvOrderAll.setOnClickListener(this);
        mTvObligation.setOnClickListener(this);
        mTvAccountPaid.setOnClickListener(this);
        mTvCanceled.setOnClickListener(this);
        mTvAddress.setOnClickListener(this);
        mTvCoupons.setOnClickListener(this);
        mRlClearCache.setOnClickListener(this);
        mTvFeedback.setOnClickListener(this);
        mRlPhone.setOnClickListener(this);

        initData();
    }

    private void initData() {
        initLoginData();
    }

    private void initLoginData() {
        if (mTvCache == null || mTvUserName == null) {
            return;
        }

        boolean isLogin = AppProfile.getUserInfo().isLogin();
        if (isLogin) {
            User user = AppProfile.getUserInfo().getUser();
            if (!TextUtils.isEmpty(user.getNickname()) ||
                    !TextUtils.isEmpty(user.getSignature()) ||
                    !TextUtils.isEmpty(user.getPhotoUrl())) {
                mLoginData = new LoginData(user);
                mTvUserName.setText(mLoginData.getNickname());
                mTvProfile.setText(mLoginData.getSignature());
                ImageUtils.setCircleUrl(mIvUserIcon, mLoginData.getPhotoUrl());
            } else {
                String passId = AppProfile.getUserInfo().getPassId();
                Observable<Response<LoginData>> api = RetrofitHelper.getLoginApi().getUserInfo(passId);
                RetrofitHelper.subscript(api, new Action1<Response<LoginData>>() {
                    @Override
                    public void call(Response<LoginData> response) {
                        if (response != null && "OK".equals(response.getStatus())
                                && response.getData() != null) {
                            mLoginData = response.getData();
                            mTvUserName.setText(mLoginData.getNickname());
                            mTvProfile.setText(mLoginData.getSignature());
                            ImageUtils.setCircleUrl(mIvUserIcon, mLoginData.getPhotoUrl());
                        }
                    }
                });
            }
        } else {
            mLoginData = null;
        }

        setVisibleWhenLogin(isLogin);

        mTvCache.setText(CacheUtils.getCacheSize(mContext));
    }

    private void setVisibleWhenLogin(boolean isLogin) {
        int visible = isLogin ? View.VISIBLE : View.GONE;
        int gone = !isLogin ? View.VISIBLE : View.GONE;
        mTvUserName.setVisibility(visible);
        mTvProfile.setVisibility(visible);
        mIvGo.setVisibility(visible);
        mTvNoLogin.setVisibility(gone);

        if (!isLogin) {
            mIvUserIcon.setImageResource(R.drawable.ic_user_icon);
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.MyCenterFragment_rl_user_info://个人资料
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        if (mLoginData != null) {
                            GeneralActivity.startForResult(mContext, GeneralActivity.USER_INFO, "个人资料", mLoginData);
                        } else {
                            ToastUtil.show("网络延迟");
                        }
                    }
                });
                break;
            case R.id.MyCenterFragment_tv_my_works://我的作品
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.start(mContext, GeneralActivity.MY_WORKS, "我的作品");
                    }
                });
                break;
            case R.id.MyCenterFragment_tv_material_depot://素材库
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.start(mContext, GeneralActivity.MATERIAL_REPERTORY, "素材库");
                    }
                });
                break;
            case R.id.MyCenterFragment_tv_order_all://全部订单
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.start(mContext, GeneralActivity.MY_ORDERS, "我的订单", 0);
                    }
                });
                break;
            case R.id.MyCenterFragment_tv_obligation://待付款
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.start(mContext, GeneralActivity.MY_ORDERS, "我的订单", 1);
                    }
                });
                break;
            case R.id.MyCenterFragment_tv_account_paid://已付款
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.start(mContext, GeneralActivity.MY_ORDERS, "我的订单", 2);
                    }
                });
                break;
            case R.id.MyCenterFragment_tv_canceled://已取消
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.start(mContext, GeneralActivity.MY_ORDERS, "我的订单", 3);
                    }
                });
                break;
            case R.id.MyCenterFragment_tv_address://地址管理
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.start(mContext, GeneralActivity.ORDER_ADDRESS, "收货地址");
                    }
                });
                break;
            case R.id.MyCenterFragment_tv_coupons://优惠券
                AppProfile.getUserInfo().startLoginActivity(mContext, new Action0() {
                    @Override
                    public void call() {
                        GeneralActivity.start(mContext, GeneralActivity.COUPON, "优惠券");
                    }
                });
                break;
            case R.id.MyCenterFragment_rl_clear_cache://清理缓存
                CacheUtils.clearAppCache(mContext, new Action0() {
                    @Override
                    public void call() {
                        mTvCache.setText("0M");
                    }
                });
                break;
            case R.id.MyCenterFragment_tv_feedback://意见反馈
                GeneralActivity.start(mContext, GeneralActivity.FEEDBACK, "意见反馈");
                break;
            case R.id.MyCenterFragment_rl_phone://客服电话
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:400-6690-999"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != MainActivity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case GeneralActivity.REQUEST_CODE:
                String name = data.getStringExtra(UserInfoFragment.USER_NAME);
                String profile = data.getStringExtra(UserInfoFragment.PERSONALIZED);
                String iconPath = data.getStringExtra(UserInfoFragment.USER_ICON);
                String gender = data.getStringExtra(UserInfoFragment.GENDER);
                String birthday = data.getStringExtra(UserInfoFragment.BIRTHDAY);
                String city = data.getStringExtra(UserInfoFragment.CITY);
                isRun(name, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mTvUserName.setText(s);
                        mLoginData.setNickname(s);
                    }
                });
                isRun(profile, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mTvProfile.setText(s);
                        mLoginData.setSignature(s);
                    }
                });
                isRun(iconPath, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        ImageUtils.setCircleUrl(mIvUserIcon, s);
                        mLoginData.setPhotoUrl(s);
                    }
                });
                isRun(gender, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mLoginData.setSex(s);
                    }
                });
                isRun(birthday, new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mLoginData.setBirthday(s);
                    }
                });
                if (city.contains("-") && city.length() > 3) {
                    String[] addressArr = city.split("-");
                    isRun(addressArr[0], new Action1<String>() {
                        @Override
                        public void call(String s) {
                            mLoginData.setProvinceName(s);
                        }
                    });
                    isRun(addressArr[1], new Action1<String>() {
                        @Override
                        public void call(String s) {
                            mLoginData.setCityName(s);
                        }
                    });
                    isRun(addressArr[2], new Action1<String>() {
                        @Override
                        public void call(String s) {
                            mLoginData.setCountyName(s);
                        }
                    });
                }
                AppProfile.getUserInfo().update(mLoginData);
                break;
            case NoLoginFragment.REQUEST_CODE:
                initLoginData();
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void isRun(String text, Action1<String> action) {
        if (!TextUtils.isEmpty(text)) {
            action.call(text);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_setting) {
            GeneralActivity.startForResult(mContext, GeneralActivity.SETTING, "设置", mLoginData);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void refreshData() {
        initLoginData();
    }

    @Override
    public void initShoppingItemNum() {

    }
}
